﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using nanoCMS.Core.Concrete;

namespace nanoCMS.Core.Providers {
	public class LanguageProvider {
		private readonly Entities entities;
		private const string LangCacheKey = "LangData";
		private CacheProvider cacheProvider = CacheProvider.Default;

		public LanguageProvider(Entities entities) {
			this.entities = entities;
		}

		public Language Get(int id) {
			if(!cacheProvider.Contains(LangCacheKey))
			{
				cacheProvider.Add(LangCacheKey, entities.Languages.ToList());
			}
			List<Language> data = cacheProvider.Get(LangCacheKey) as List<Language>;
			if (data == null) throw new Exception("Cache provider out of order");
			if (!data.Any(x => x.LangID == id)) return GetDefault();
				
			return data.SingleOrDefault(x => x.LangID == id);
		}

		public Language Get(string shortCode) {
			return entities.Languages.SingleOrDefault(x => x.ShortCode == shortCode);
		}

		public Language GetDefault() {
			if (!cacheProvider.Contains(LangCacheKey)) {
				cacheProvider.Add(LangCacheKey, entities.Languages.ToList());
			}
			List<Language> data = cacheProvider.Get(LangCacheKey) as List<Language>;
			if (data == null) throw new Exception("Cache provider out of order");
			return data.SingleOrDefault(x => x.IsPrimary == true);
		}

		public void SetDefault(int newId) {
			var currentDefault = GetDefault();
			var newDefault = Get(newId);
			if (currentDefault == null || newDefault == null) throw new Exception();

			currentDefault.IsPrimary = null;
			newDefault.IsPrimary = true;
			entities.SaveChanges();
		}

		//TODO: add/edit
	}
}
